﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Heritage.Identity;
using System.Threading;
using Heritage.Codebox;
using System.ComponentModel;

namespace Heritage
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        private static BackgroundWorker wrk = null;

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}/{id2}", // URL with parameters
                new { controller = "Auth", action = "Welcome", id = "", id2="" } // Parameter defaults
            );
        }

        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            HttpCookie authCookie = Request.Cookies[
                     FormsAuthentication.FormsCookieName];
            if (authCookie != null)
            {
                FormsAuthenticationTicket authTicket =
                       FormsAuthentication.Decrypt(authCookie.Value);
                if (Utils.UserExists(authTicket.Name)) {
                    CustomIdentity id = GetUserIdentity(authTicket.Name);
                    CustomPrincipal newUser = new CustomPrincipal(id);
                    Context.User = newUser;
                    Thread.CurrentPrincipal = newUser;
                }
                else 
                {
                    CustomPrincipal user = new CustomPrincipal(new CustomIdentity(""));
                    Thread.CurrentPrincipal = user;
                    Context.User = user;
                }
            }
            else
            {
                CustomPrincipal user = new CustomPrincipal(new CustomIdentity(""));
                Thread.CurrentPrincipal = user;
                Context.User = user;
            }
        }

        private CustomIdentity GetUserIdentity(string str)
        {
            CustomIdentity id = new CustomIdentity(str);
            return id;
            
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);
        }



        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown

        }
  
    }
}